package com.mingtu.jgspatrol.activity;

import static com.mingtu.common.utils.MyUtills.getBounds;
import static com.mingtu.jgspatrol.utils.MyConstant.INFO_WINDOW_OFF_SET_Y;

import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.TileOverlay;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.gson.factory.GsonFactory;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.activity.NaviMapActivity;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.ConvertLatlng;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.common.utils.StatusBarUtil;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.EcDequiBean;
import com.mingtu.jgspatrol.databinding.ActivityCommonEquiMapBinding;
import com.mingtu.jgspatrol.utils.MarkerOptionsUtils;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.mingtu.jgspatrol.view.CommonMapView;
import com.mingtu.infrared.adapter.EquiSingleChoiceTextAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class EcologyMapActivity extends MyBaseActivity<ActivityCommonEquiMapBinding> implements AMap.OnMarkerClickListener,
        AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener, AMap.OnMapTouchListener {
    private AMap aMap;
    private List<Marker> markerList = new ArrayList<>();
    private View infoWindow;
    private int position;
    private TileOverlay tileOverlay;
    private boolean isSwitch = true;
    private ImmersionBar immersionBar;
    private Marker clickMarker;
    private CommonMapView commonMapView;
    private String[] ecologyArray = null; //此账号和markerList存在对应关系
    private List<String> ecologyList;
    private EquiSingleChoiceTextAdapter filteDepartAdapter;
    private EquiSingleChoiceTextAdapter filteEquiAdapter;
    private List<EcDequiBean.DataBean> dataBeans;
    private List<String> deptNameList = new ArrayList<>();
    private List<String> deptEquiList = new ArrayList<>();
    private String equiName;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_equi_map;
    }

    @Override
    protected void initView() {
        hideHeadView();
        StatusBarUtil.addStatusBarHeight(binding.statusBarView);
        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();

        int statusBarHeight = BarUtils.getStatusBarHeight();//单位是px

        ViewGroup.LayoutParams layoutParams = (ViewGroup.LayoutParams) binding.viewBlock.getLayoutParams();
        layoutParams.height = statusBarHeight;
        binding.viewBlock.setLayoutParams(layoutParams);
    }

    @Override
    protected void initData() {
//部门列表
        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(this);
        flm1.setFlexWrap(FlexWrap.WRAP);
        flm1.setFlexDirection(FlexDirection.ROW);
        flm1.setAlignItems(AlignItems.STRETCH);
        flm1.setJustifyContent(JustifyContent.FLEX_START);
        binding.recyclerDepart.setLayoutManager(flm1);

        filteDepartAdapter = new EquiSingleChoiceTextAdapter(BaseApplication.getBaseApplication(), null);
        binding.recyclerDepart.setAdapter(filteDepartAdapter);
        filteDepartAdapter.setOnItemClickListener(new EquiSingleChoiceTextAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                filteDepartAdapter.upData(position);
                if (deptNameList != null && deptNameList.size() > 0) {
                    String currentDeptName = deptNameList.get(position);
                    List<String> equiList = getDeptEqui(currentDeptName);
                    filteEquiAdapter.upData(equiList);
                    equiName = null;
                }
            }
        });

        //设备列表
        FlexboxLayoutManager flm2 = new FlexboxLayoutManager(this);
        flm2.setFlexWrap(FlexWrap.WRAP);
        flm2.setFlexDirection(FlexDirection.ROW);
        flm2.setAlignItems(AlignItems.STRETCH);
        flm2.setJustifyContent(JustifyContent.FLEX_START);
        binding.recyclerEqui.setLayoutManager(flm2);

        filteEquiAdapter = new EquiSingleChoiceTextAdapter(BaseApplication.getBaseApplication(), null);
        binding.recyclerEqui.setAdapter(filteEquiAdapter);
        filteEquiAdapter.setOnItemClickListener(new EquiSingleChoiceTextAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                filteEquiAdapter.upData(position);
                if (deptEquiList.size() > 0) {
                    equiName = deptEquiList.get(position);
                }
            }
        });
        addClickListener(this,binding.ivSwitch,binding.ivBack,binding.ivListMode,binding.tvCancel,binding.tvSure,binding.tvReset);
    }

    @Override
    protected void getData() {
        position = getIntent().getIntExtra("position", 404);
    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        commonMapView = findViewById(R.id.common_map_view);
        commonMapView.setMapParam(savedInstanceState);
        aMap = commonMapView.getAMap();
        aMap.setOnMarkerClickListener(this);
        aMap.setInfoWindowAdapter(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.addOnMapTouchListener(this);
//        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                getDequiList();

            }
        });
        //自定义瓦片
        tileOverlay = commonMapView.getTileOverlay();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                ActivityUtil.removeActivity(this);
                break;
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    tileOverlay.setVisible(false);
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    tileOverlay.setVisible(true);
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
            case R.id.iv_list_mode:
                openRightDrawer();
                break;
            case R.id.tv_cancel:
                closeRightDrawers();
                break;
            case R.id.tv_reset:
                closeRightDrawers();
                filteDepartAdapter.resetData();
                filteEquiAdapter.resetData();
                filteEquiAdapter.upData(ecologyList);
                equiName = null;
                break;
            case R.id.tv_sure:
                closeRightDrawers();
                if (equiName != null) {
                    //markerList 、infraredList 存储的数据是对应关系
                    if (ecologyList.indexOf(equiName) != -1) {
                        int index = ecologyList.indexOf(equiName);
                        clickMarker = markerList.get(index);
                        clickMarker.showInfoWindow();
                        aMap.animateCamera(CameraUpdateFactory.changeLatLng(clickMarker.getPosition()));
                        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                    }
                } else {
                    ToastUtils.showLong("请选择设备");
                }

                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (markerList.size() > 0) {
            markerList.clear();
        }

        super.onDestroy();
    }

    /**
     * 设备信息
     */
    private void getDequiList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deviceType", null);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_EC_DEVICE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            EcDequiBean ecDequiBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ecDequiBean = new EcDequiBean();
                                ecDequiBean = gson.fromJson(result, EcDequiBean.class);
                                dataBeans = ecDequiBean.getData();
                                if (dataBeans != null) {
                                    if (dataBeans.size() > 0) {
                                        //气象
                                        ApplicationInfo appInfo1 = context.getApplicationInfo();
                                        ArrayList<BitmapDescriptor> weatherGif = new ArrayList<BitmapDescriptor>();
                                        for (int i = 1; i <= 24; i++) {
                                            int resID = getResources().getIdentifier("icon_ec" + i, "mipmap", appInfo1.packageName);
                                            weatherGif.add(BitmapDescriptorFactory.fromResource(resID));
                                        }


                                        //水文
                                        ApplicationInfo appInfo2 = context.getApplicationInfo();
                                        ArrayList<BitmapDescriptor> hydrologyGif = new ArrayList<BitmapDescriptor>();
                                        for (int i = 1; i <= 24; i++) {
                                            int resID = getResources().getIdentifier("icon_hydrology" + i, "mipmap", appInfo2.packageName);
                                            hydrologyGif.add(BitmapDescriptorFactory.fromResource(resID));
                                        }

                                        deptNameList = dataBeans.stream().map(EcDequiBean.DataBean::getDeptName).distinct().collect(Collectors.toList());
                                        if (deptNameList.size() > 0) {
                                            filteDepartAdapter.upData(deptNameList);
                                        }


                                        ecologyList = new ArrayList<>();
                                        List<LatLng> latLngs = new ArrayList<>();
                                        for (int i = 0; i < dataBeans.size(); i++) {
                                            EcDequiBean.DataBean dataBean = dataBeans.get(i);
                                            String latitude = dataBean.getLat();
                                            String longitude = dataBean.getLon();
                                            String status = dataBean.getStatus();
                                            String name = dataBean.getName();
                                            String heartTime = dataBean.getHeartTime();
                                            if (!StringUtils.isEmpty(latitude) && !StringUtils.isEmpty(longitude)) {

                                                double lat = Double.parseDouble(latitude);
                                                double lng = Double.parseDouble(longitude);
                                                String myLng = ConvertLatlng.getInstance().convertToSexagesimal(lng);
                                                String myLat = ConvertLatlng.getInstance().convertToSexagesimal(lat);

                                                boolean isOnline = false;
                                                if (!StringUtils.isEmpty(status)) {
                                                    if (status.equals("0")) { //0 离线  1在线
                                                        //如果当前时间与心跳时间的差值大于12小时，说明设备离线
                                                        isOnline = false;
                                                    } else {
                                                        isOnline = true;
                                                    }
                                                } else {
                                                    if (!StringUtils.isEmpty(heartTime)) {
                                                        long hearTimeMillis = TimeUtils.string2Millis(heartTime);
                                                        long nowMills = TimeUtils.getNowMills();
                                                        if (nowMills - hearTimeMillis > 12 * 60 * 60 * 1000) {
                                                            //如果当前时间与心跳时间的差值大于12小时，说明设备离线
                                                            isOnline = false;
                                                        } else {
                                                            isOnline = true;
                                                        }
                                                    }
                                                }

                                                LatLng location = new LatLng(lat, lng);
                                                latLngs.add(location);

                                                //添加Marker
                                                if (isOnline) {

                                                    if (name.indexOf("气象") != -1) {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions2(location, name, INFO_WINDOW_OFF_SET_Y, weatherGif));
                                                        markerList.add(marker);
                                                    } else {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions2(location, name, INFO_WINDOW_OFF_SET_Y, hydrologyGif));
                                                        markerList.add(marker);
                                                    }

                                                } else {

                                                    if (name.indexOf("气象") != -1) {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions1(location, name, INFO_WINDOW_OFF_SET_Y, R.mipmap.icon_ec_offline));
                                                        markerList.add(marker);
                                                    } else {
                                                        Marker marker = aMap.addMarker(MarkerOptionsUtils.getMarkerOptions1(location, name, INFO_WINDOW_OFF_SET_Y, R.mipmap.icon_hydrology_offline));
                                                        markerList.add(marker);
                                                    }
                                                }

                                                if (!StringUtils.isEmpty(name)) {
                                                    ecologyList.add(name);
                                                } else {
                                                    ecologyList.add(myLat + "," + myLng);
                                                }


                                            }
                                        }
                                        deptEquiList = ecologyList;
                                        //展示全部设备
                                        filteEquiAdapter.upData(ecologyList);

                                        if (latLngs.size() > 0) {
                                            if (position == 404) {
                                                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(getBounds(latLngs), 380));
                                            } else {
                                                //此处的请求设备的方法和前面数据请求数据的方法 为同一个方法，顺序一样，一次可以用这种方式获取经纬度
                                                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLngs.get(position)));
                                            }
                                        }

                                    }
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    @Override
    public View getInfoWindow(Marker marker) {
        //关闭了点击事件，此处逻辑没有展示效果
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(this).inflate(R.layout.bubble_view2, null);
        }

        render(marker, infoWindow);
        return infoWindow;

    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        marker.hideInfoWindow();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.showInfoWindow();
        clickMarker = marker;
        return false;
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (clickMarker != null) {
            boolean b = clickMarker.isInfoWindowShown();
            if (b) {
                clickMarker.hideInfoWindow();
            }
        }
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        String windowInfo = marker.getTitle();
        TextView title = ((TextView) view.findViewById(R.id.title));
        title.setText(windowInfo);

        LinearLayout layoutMarker = (LinearLayout) view.findViewById(R.id.layout);
        layoutMarker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //防止点击事件和touch事件冲突，所以采用此种方式跳转

                LatLng latLng = marker.getPosition();
                String lngStr = latLng.longitude + "";
                String latStr = latLng.latitude + "";

                Bundle bundle = new Bundle();
                bundle.putString("lng", lngStr);
                bundle.putString("lat", latStr);
                bundle.putBoolean("isFire", false);
                IntentUtils.getInstance().readyGo(EcologyMapActivity.this, NaviMapActivity.class, bundle);

            }
        });
    }

    /**
     * 显示列表
     */
    public void showListPop() {
        if (ecologyList != null && ecologyList.size() >= 0) {
            ecologyArray = new String[ecologyList.size()];
            for (int i = 0; i < ecologyList.size(); i++) {
                ecologyArray[i] = ecologyList.get(i);
            }
            new XPopup.Builder(this)
                    .hasShadowBg(true)
                    .maxHeight(ScreenUtils.getScreenHeight() / 2)
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .asCenterList("列表模式", ecologyArray,
                            new OnSelectListener() {
                                @Override
                                public void onSelect(int position, String text) {
                                    Marker marker = markerList.get(position);
                                    marker.showInfoWindow();
                                    aMap.animateCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
                                    aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM));
                                }
                            }).show();
        }

    }

    /**
     * 根据保护区名字查询设备
     *
     * @param currentDeptName
     * @return
     */
    private List<String> getDeptEqui(String currentDeptName) {
        deptEquiList = new ArrayList<>();
        if (dataBeans != null && dataBeans.size() > 0) {
            for (EcDequiBean.DataBean listBean : this.dataBeans) {
                String deptName = listBean.getDeptName();
                if (currentDeptName.equals(deptName)) {
                    String equi = listBean.getName();
                    deptEquiList.add(equi);
                }
            }
            return deptEquiList;
        } else {
            return deptEquiList;
        }
    }

    /**
     * 关闭右侧边栏
     */
    public void closeRightDrawers() {
        binding.layoutDrawer.closeDrawer(binding.layoutRightDrawer);
    }

    /**
     * 打开右侧边栏
     */
    public void openRightDrawer() {
        binding.layoutDrawer.openDrawer(binding.layoutRightDrawer);
    }
}